<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-12-19 16:44:58
 * @Description: 使用 Element-UI 实现数据展示并支持导出Excel
-->
<template>
    <el-card class="Irrigation-card">
        <el-row style="height: 99.8vh;">
            <!-- 左侧布局 -->
            <el-col :span="8" style="border-right: 1px solid #ebeef5; padding: 20px; overflow-y: auto;">
                <el-card>
                    <h1 style="margin-bottom: 20px;">灌溉数据查询系统</h1>
                    <!-- 筛选条件 -->
                    <el-row :gutter="20" class="filter-section">
                        <el-col :span="24">
                            <el-form-item label="年份选择">
                                <el-select v-model="filters.selectedYears" multiple placeholder="请选择年份">
                                    <el-option v-for="year in filters.years" :key="year" :label="year" :value="year" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="月份选择">
                                <el-select v-model="filters.selectedMonth" placeholder="请选择月份">
                                    <el-option label="全年" value="" />
                                    <el-option v-for="month in filters.months" :key="month.value" :label="month.label"
                                        :value="month.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="作物选择">
                                <el-checkbox-group v-model="filters.selectedCrops">
                                    <el-checkbox v-for="crop in filters.crops" :key="crop" :label="crop" />
                                </el-checkbox-group>
                            </el-form-item>
                        </el-col>

                        <el-col :span="24" class="filter-buttons">
                            <!-- 添加数据按钮 -->
                            <el-button type="primary" style="margin-top: 20px;" @click="openAddDialog">新增数据</el-button>
                            <div>
                                <el-button type="primary" @click="loadData">查询</el-button>
                                <el-button type="success" @click="exportExcel">导出Excel</el-button>
                            </div>
                        </el-col>
                    </el-row>
                    <!-- 数据表格 -->
                    <el-table :data="filteredData" :border="true" height="600" size="small">
                        <el-table-column prop="region" width="60" label="灌区" />
                        <el-table-column prop="crop" width="60" label="作物类型" />
                        <el-table-column prop="year" width="60" label="年份" />
                        <el-table-column prop="month" width="60" label="月份" />
                        <el-table-column prop="area" width="60" label="作物面积 (万亩)" />
                        <el-table-column prop="irrigation" width="60" label="灌溉面积 (万亩)" />
                        <el-table-column prop="water" width="60" label="净灌溉用水量 (万方)" />
                        <el-table-column label="灌溉水有效利用系数">
                            <template #default="scope">
                                {{ calculateEfficiency(scope.row.area, scope.row.irrigation, scope.row.water) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="100" fixed="right">
                            <template #default="scope">
                                <el-button type="text" @click="editData(scope.row)">编辑</el-button>
                                <el-button type="text" @click="deleteData(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-col>

            <!-- 右侧布局 -->
            <el-col :span="16" style="padding: 20px; overflow: hidden;">
                <!-- 图表展示 -->
                <div id="chart" style="width: 100%; height: 40%;"></div>
            </el-col>

            <!-- 数据编辑/新增弹窗 -->
            <el-dialog v-model="dialogVisible" title="编辑数据">
                <el-form :model="editForm" label-width="180px">
                    <el-form-item label="灌区">
                        <el-input v-model="editForm.region" />
                    </el-form-item>
                    <el-form-item label="作物类型">
                        <el-input v-model="editForm.crop" />
                    </el-form-item>
                    <el-form-item label="年份">
                        <el-input type="number" v-model="editForm.year" />
                    </el-form-item>
                    <el-form-item label="月份">
                        <el-input v-model="editForm.month" />
                    </el-form-item>
                    <el-form-item label="作物面积 (万亩)">
                        <el-input type="number" v-model="editForm.area" />
                    </el-form-item>
                    <el-form-item label="灌溉面积 (万亩)">
                        <el-input type="number" v-model="editForm.irrigation" />
                    </el-form-item>
                    <el-form-item label="净灌溉用水量 (万方)">
                        <el-input type="number" v-model="editForm.water" />
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveData">保存</el-button>
                </div>
            </el-dialog>
        </el-row>
    </el-card>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from "vue";
import * as echarts from "echarts";
import * as XLSX from "xlsx";

const filters = reactive({
    years: [2024],
    months: [
        { value: 1, label: "1月" },
        { value: 2, label: "2月" },
        { value: 3, label: "3月" }
    ],
    crops: ["小麦", "葵花", "玉米", "苜蓿"],
    selectedYears: [],
    selectedMonth: "",
    selectedCrops: []
});

const data = reactive([
    { region: "灌区", crop: "小麦", year: 2024, month: "1月", area: 50, irrigation: 40, water: 3000 },
    { region: "灌区", crop: "小麦", year: 2024, month: "2月", area: 55, irrigation: 42, water: 3200 },
    { region: "灌区", crop: "小麦", year: 2024, month: "3月", area: 60, irrigation: 50, water: 3500 },
    { region: "灌区", crop: "葵花", year: 2024, month: "1月", area: 30, irrigation: 25, water: 2000 },
    { region: "灌区", crop: "葵花", year: 2024, month: "2月", area: 35, irrigation: 28, water: 2200 },
    { region: "灌区", crop: "玉米", year: 2024, month: "1月", area: 45, irrigation: 35, water: 2500 },
    { region: "灌区", crop: "玉米", year: 2024, month: "2月", area: 50, irrigation: 40, water: 2700 },
    { region: "灌区", crop: "苜蓿", year: 2024, month: "1月", area: 40, irrigation: 30, water: 2100 },
    { region: "灌区", crop: "苜蓿", year: 2024, month: "2月", area: 50, irrigation: 40, water: 2700 }
]);

const filteredData = computed(() => {
    return data.filter(item =>
        (filters.selectedYears.length === 0 || filters.selectedYears.includes(item.year)) &&
        (filters.selectedMonth === "" || item.month === filters.months.find(m => m.value === parseInt(filters.selectedMonth))?.label) &&
        (filters.selectedCrops.length === 0 || filters.selectedCrops.includes(item.crop))
    );
});

const dialogVisible = ref(false);
const editForm = reactive({
    region: "",
    crop: "",
    year: 2024,
    month: "",
    area: 0,
    irrigation: 0,
    water: 0
});

function calculateEfficiency(area: number, irrigation: number, water: number): string {
    const efficiency = (water / (area * (irrigation / area))) / 100;
    return efficiency.toFixed(2);
}

function renderChart() {
    const chartDom = document.getElementById("chart") as HTMLElement;
    const chart = echarts.init(chartDom);
    const option = {
        title: { 
            text: "灌溉水有效利用系数变化" 
        },
        xAxis: { 
            type: "category", 
            data: filteredData.value.map(row => `${row.crop}-${row.month}`) 
        },
        yAxis: { 
            type: "value" 
        },
        tooltip: {
            trigger: 'item', // 鼠标悬浮触发
            formatter: params => {
                // 显示数值，带百分号
                return `${params.name}: ${params.value}`;
            }
        },
        series: [{
            data: filteredData.value.map(row => parseFloat(calculateEfficiency(row.area, row.irrigation, row.water))),
            type: "bar",
            label: {
                show: false // 默认不显示数值，避免与鼠标悬浮的效果冲突
            },
            emphasis: {
                focus: 'series', // 鼠标悬浮时高亮系列
                itemStyle: {
                    color: '#409eff', // 改变悬浮柱子颜色
                }
            }
        }]
    };
    chart.setOption(option);
}


function loadData() {
    renderChart();
}

function exportExcel() {
    const ws = XLSX.utils.json_to_sheet(filteredData.value.map(item => ({
        灌区: item.region,
        作物类型: item.crop,
        年份: item.year,
        月份: item.month,
        作物面积: item.area,
        灌溉面积: item.irrigation,
        净灌溉用水量: item.water,
        有效利用系数: calculateEfficiency(item.area, item.irrigation, item.water)
    })));

    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "灌溉数据");
    XLSX.writeFile(wb, "灌溉数据.xlsx");
}

function openAddDialog() {
    Object.assign(editForm, { region: "", crop: "", year: 2024, month: "", area: 0, irrigation: 0, water: 0 });
    dialogVisible.value = true;
}

function editData(row: any) {
    Object.assign(editForm, row);
    dialogVisible.value = true;
}

function deleteData(row: any) {
    const index = data.indexOf(row);
    if (index !== -1) data.splice(index, 1);
    loadData();
}

function saveData() {
    if (!editForm.region || !editForm.crop || !editForm.month || !editForm.area || !editForm.irrigation || !editForm.water) {
        alert("请完整填写所有字段");
        return;
    }

    const existing = data.find(
        item =>
            item.region === editForm.region &&
            item.crop === editForm.crop &&
            item.year === editForm.year &&
            item.month === editForm.month
    );

    if (existing) {
        Object.assign(existing, editForm);
    } else {
        data.push({ ...editForm });
    }

    dialogVisible.value = false;
    loadData();
}

onMounted(() => {
    loadData();
});
</script>

<style lang="scss" scoped>
.filter-section {
    margin-bottom: 20px;
}

.filter-buttons {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.dialog-footer{
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
<style lang="scss">
.Irrigation-card>.el-card__body  {
    padding: 0;
}
</style>
